from luffyapi.utils.response import APIResponse

# 登录接口，自动生成路由，post请求，跟数据有关
from rest_framework.viewsets import ViewSetMixin, ViewSet
from rest_framework.decorators import action
from .serializers import UserModelSerializer,UserPhoneMOdelSerializer,UserRegisterModelSerializer
from . import models
import re
from luffyapi.libs.tx_sms import send, get_code


class UserView(ViewSet):
    @action(methods=['POST'], detail=False)
    def login(self, request, *args, **kwargs):
        # 序列化类
        ser = UserModelSerializer(data=request.data)
        if ser.is_valid():
            # 登陆成功
            token = ser.context['token']
            user = ser.context['user']
            return APIResponse(token=token, username=user.username, id=user.id)
        else:
            # 登陆失败
            return APIResponse(code=101, msg='用户名或密码错误')

    @action(methods=['POST'], detail=False)
    def login_phone(self, request, *args, **kwargs):
        # 序列化类
        ser = UserPhoneMOdelSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context['token']
        user = ser.context['user']
        return APIResponse(token=token,username=user.username,id=user.id)

    @action(methods=['POST'], detail=False)
    def register(self, request, *args, **kwargs):
        # 序列化类
        ser = UserRegisterModelSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return APIResponse(code=100, msg='注册成功')


    # 手机号是否存在接口 get user/check_phone?phone=1825200
    # 自动生成路由，直接写在原来写login的视图中
    @action(methods=['GET'], detail=False)
    def check_phone(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        print(phone)
        if re.match('^1[3-9][0-9]{9}$', phone):
            user = models.User.objects.filter(mobile=phone).first()
            if user:
                return APIResponse(msg='手机号存在')
            else:
                return APIResponse(code=101, msg='手机号不存在')
        else:
            return APIResponse(code=102, msg='手机号不合法')


from rest_framework.decorators import action
from django.core.cache import cache
from django.conf import settings
from .throttlings import SMSThrottle


class SmsView(ViewSet):
    throttle_classes = [SMSThrottle]

    # 发送短信接口
    # 限制同一个手机号一分钟只能发送一次
    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        phone = request.query_params.get('phone')
        print(phone)
        if phone:
            if re.match('^1[3-9][0-9]{9}$', phone):
                code = get_code()
                res = send(phone, code)
                # 短信验证码存在django缓存中，默认存在内存，redis
                cache.set(settings.SMS_PHONE_CACHE % phone, code, 60)
                if res:
                    return APIResponse(msg='短信发送成功')
                else:
                    return APIResponse(code=101, msg='短信发送失败')
            else:
                return APIResponse(code=102, msg='手机号不合法')
        else:
            return APIResponse(code=103, msg='没有携带手机号')
